import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { categoryDB } from '@/utils/database'
import type { Category } from '@/types'
import { showToast } from 'vant'

export const useCategoryStore = defineStore('category', () => {
  // 状态
  const categories = ref<Category[]>([])
  const loading = ref(false)

  // 计算属性
  const incomeCategories = computed(() => 
    categories.value.filter(c => c.type === 'income' && c.isActive)
  )

  const expenseCategories = computed(() => 
    categories.value.filter(c => c.type === 'expense' && c.isActive)
  )

  // 获取分类列表
  const fetchCategories = async (type?: 'income' | 'expense') => {
    try {
      loading.value = true
      const response: any = await categoryDB.getAll({ type })

      if (response.status === 'success' && response.data) {
        categories.value = response.data.categories
      }
    } catch (error) {
      console.error('获取分类失败:', error)
      showToast('获取分类失败')
    } finally {
      loading.value = false
    }
  }

  // 创建分类
  const createCategory = async (data: Omit<Category, 'id'>) => {
    try {
      loading.value = true
      const response: any = await categoryDB.create(data)

      if (response.status === 'success' && response.data) {
        // 重新获取分类列表以确保数据同步
        await fetchCategories()
        showToast('创建成功')
        return response.data
      }
    } catch (error) {
      console.error('创建分类失败:', error)
      showToast('创建失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新分类
  const updateCategory = async (id: number, data: Partial<Category>) => {
    try {
      loading.value = true
      const response: any = await categoryDB.update(id, data)

      if (response.status === 'success' && response.data) {
        const index = categories.value.findIndex(c => c.id === id)
        if (index !== -1) {
          categories.value[index] = { ...categories.value[index], ...response.data }
        }
        showToast('更新成功')
        return response.data
      }
    } catch (error) {
      console.error('更新分类失败:', error)
      showToast('更新失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 删除分类
  const deleteCategory = async (id: number) => {
    try {
      loading.value = true
      const response: any = await categoryDB.delete(id)

      if (response.status === 'success') {
        const index = categories.value.findIndex(c => c.id === id)
        if (index !== -1) {
          categories.value.splice(index, 1)
        }
        showToast('删除成功')
        return true
      }
    } catch (error) {
      console.error('删除分类失败:', error)
      showToast('删除失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 初始化默认分类（离线模式下数据库初始化时已自动完成）
  const initializeCategories = async () => {
    try {
      loading.value = true
      // 离线模式下，分类在数据库初始化时已自动创建，这里只需重新获取
      await fetchCategories()
      showToast('初始化成功')
      return true
    } catch (error) {
      console.error('初始化分类失败:', error)
      showToast('初始化失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取分类
  const getCategoryById = (id: number | string) => {
    const numId = typeof id === 'string' ? parseInt(id) : id
    return categories.value.find(c => c.id === numId)
  }

  // 重置状态
  const reset = () => {
    categories.value = []
  }

  return {
    // 状态
    categories,
    loading,
    
    // 计算属性
    incomeCategories,
    expenseCategories,
    
    // 方法
    fetchCategories,
    createCategory,
    updateCategory,
    deleteCategory,
    initializeCategories,
    getCategoryById,
    reset
  }
})